﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
using XISoft.AppCreator.Util.CompileHelper;
using XISoft;

namespace XISoft.AppCreator.TplEngine.Syntax
{

    class Tags
    {
        private const String strPerrernFlag = @"#\{(?<express>.*)\}";

        private Hashtable _variables;
        private string _values;
        private int _pos, _start;
        public Tags(String str, Hashtable variables)
        {
            _values = str;
            _variables = variables;
            _pos = 0;
            _start = 0;
        }

        /// <summary>
        /// 标记名
        /// </summary>
        public String keyName
        {
            get { return _values.Substring(_start, _pos - _start); }
        }

        /// <summary>
        /// 标记值
        /// </summary>
        public Object keyValue
        {
            get { return getObject(_variables, keyName.Trim()); }
        }

        /// <summary>
        /// 标记起始位置
        /// </summary>
        public int Index
        {
            get { return _start; }
        }

        /// <summary>
        /// 标记长度
        /// </summary>
        public int Length
        {
            get { return _pos - _start + 1; }
        }

        /// <summary>
        /// 获取下一个标记
        /// </summary>
        /// <returns>true有下一个标记</returns>
        public Boolean next()
        {
            while (_pos < _values.Length - 3 && (_values[_pos] != strPerrernFlag[0] || _values[_pos + 1] != strPerrernFlag[2])) _pos++;
            if (_pos >= _values.Length - 3) return false;

            _start = _pos;
            while (_pos < _values.Length && _values[_pos] != strPerrernFlag[strPerrernFlag.Length - 1]) _pos++;
            if (_pos >= _values.Length) return false;
            _pos++;

            return true;
        }

        /// <summary>
        /// 标记对应的数据
        /// </summary>
        /// <param name="tagName">标记名</param>
        /// <returns></returns>
        public static Object getObject(Hashtable variables, String tagName)
        {
            MatchCollection type = Regex.Matches(tagName, strPerrernFlag, RegexOptions.IgnoreCase | RegexOptions.Compiled);
            return CompileCommon.GetFlagValue(variables, type[0].Groups["express"].Value.Trim());
        }
    }
}
